package com.fz.us.oa.web.controller.com;

import com.fz.us.admin.base.bean.BaseEnumManager;
import com.fz.us.admin.base.bean.jqgrid.JqGridFilter;
import com.fz.us.admin.base.bean.jqgrid.JqGridPager;
import com.fz.us.admin.base.bean.search.SearchEnum;
import com.fz.us.admin.base.bean.search.order.Order;
import com.fz.us.admin.base.bean.search.result.SearchResultPaging;
import com.fz.us.admin.base.bean.search.rule.Rule;
import com.fz.us.admin.base.bean.search.rule.RuleHelper;
import com.fz.us.admin.company.bean.FlowEnum;
import com.fz.us.admin.company.entity.Company;
import com.fz.us.admin.company.entity.Department;
import com.fz.us.admin.company.entity.TaskEntity;
import com.fz.us.admin.company.entity.User;
import com.fz.us.admin.company.service.DepartmentService;
import com.fz.us.admin.company.service.DutyService;
import com.fz.us.admin.company.service.TaskEntityService;
import com.fz.us.admin.company.service.UserService;
import com.fz.us.oa.core.entity.com.Asset;
import com.fz.us.oa.core.entity.com.AssetFlit;
import com.fz.us.oa.core.entity.com.AssetUse;
import com.fz.us.oa.core.service.com.AssetFlitService;
import com.fz.us.oa.core.service.com.AssetService;
import com.fz.us.oa.core.service.com.AssetUseService;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import com.fz.us.oa.web.spring.bind.annotation.RequestJsonParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by ZhuChunXiao on 2017/7/26.
 */
@Controller
@RequestMapping(value = "/com/assetFlit")
public class AssetFlitController extends BaseController {
    private static final long serialVersionUID = 1217596605416563617L;

    @Autowired
    private AssetFlitService assetFlitService;
    @Autowired
    private AssetService assetService;
    @Autowired
    private AssetUseService assetUseService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private UserService userService;
    @Autowired
    private DutyService dutyService;
    @Autowired
    private TaskEntityService taskEntityService;

    private Date dateApply;
    private SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
    private SimpleDateFormat monthFormat = new SimpleDateFormat("MM");
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    private Asset asset;

    /**
     * 新建，编辑页面
     */
    @RequestMapping(value = "input", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String input(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        if (StringUtils.isNotEmpty(keyId)){
            AssetFlit assetFlit=assetFlitService.get(keyId);
            model.addAttribute("keyId", keyId);
            model.addAttribute("assetFlit", assetFlit);
        }
        model.addAttribute("user", user);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/assetflit_input";
    }

    /**
     * 只读页面
     */
    @RequestMapping(value = "read", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String read(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        if(StringUtils.isNotEmpty(keyId)) {
            AssetFlit assetFlit=assetFlitService.get(keyId);
            TaskEntity taskEntity = taskEntityService.getInfoByKeyId(keyId);
            int stepNo = taskEntity.getStepNo();
            String isEdit =  isEdit(keyId);
            model.addAttribute("stepNo", stepNo);
            model.addAttribute("isEdit", isEdit);
            model.addAttribute("assetFlit", assetFlit);
        }

        model.addAttribute("keyId", keyId);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/assetflit_read";
    }

    /**
     * 保存Model数据
     */
    private AssetFlit saveModel(User user, String keyId, String assetId, String name, String oldUseDeptName, String oldUserName, String deptId, String userId) throws ParseException {

        AssetFlit assetFlit = null;
        if (StringUtils.isBlank(keyId)) {
            assetFlit = new AssetFlit();
            assetFlit.setCreater(user);
            assetFlit.setCompany(user.getCompany());
        } else {
            assetFlit = assetFlitService.get(keyId);
        }

        if (StringUtils.isNotBlank(assetId)) {
            Asset asset = assetService.get(assetId);
            if (asset != null) {
                assetFlit.setAsset(asset);
            }
        }

        if (StringUtils.isNotBlank(name)) {
            assetFlit.setName(name);
        }

        if (StringUtils.isNotBlank(oldUseDeptName)) {
            assetFlit.setOldUseDeptName(oldUseDeptName);
        }

        if (StringUtils.isNotBlank(oldUserName)) {
            assetFlit.setOldUserName(oldUserName);
        }

        if (StringUtils.isNotBlank(deptId)) {
            Department dept = departmentService.get(deptId);
            if (dept != null) {
                assetFlit.setUseDepartment(dept);
            }
        }

        if (StringUtils.isNotBlank(userId)) {
            User user1 = userService.get(userId);
            if (user1 != null) {
                assetFlit.setUser(user1);
            }
        }

        if (assetFlit.getForm() == null) {
            assetFlit.setForm("资产调拨登记表");
        }

        return assetFlit;
    }

    /**
     * 保存操作
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public Object save(@CurrentUser User user, @RequestParam(required = false) String keyId, String assetId, String name,
                       String oldUseDeptName, String oldUserName, String deptId, String userId) throws ParseException {

        Map<String,Object> rMap=new HashMap<String,Object>();
        AssetFlit assetFlit = saveModel(user,keyId,assetId,name,oldUseDeptName,oldUserName,deptId,userId);
        if(StringUtils.isNotEmpty(keyId)){
            assetFlitService.update(assetFlit);
            rMap.put("message", "更新成功");
        } else {
            assetFlitService.save(assetFlit, "com.fz.us.oa.core.entity.com.AssetFlit");
            rMap.put("message", "保存成功");
        }
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     *提交操作
     */
    @RequestMapping(value = "commit", method = RequestMethod.POST)
    public Object commit(@CurrentUser User user, @RequestParam(required = false) String keyId, String assetId, String name,
                         String oldUseDeptName, String oldUserName, String deptId, String userId,
                         String curDutyId, String comment) throws ParseException{

        Map<String,Object> rMap=new HashMap<String,Object>();
        AssetFlit assetFlit = saveModel(user,keyId,assetId,name,oldUseDeptName,oldUserName,deptId,userId);
        assetFlit.setNumStatus(1);
        assetFlit.setTxtStatus("流转中");

        if (StringUtils.isNotEmpty(keyId)) {
            assetFlitService.approve(assetFlit, dutyService.get(curDutyId), comment);
        } else {
            assetFlitService.commit(assetFlit, "com.fz.us.oa.core.entity.com.AssetFlit", dutyService.get(curDutyId));
        }

        if(assetFlit.getProcessState().name().equals("Finished")){
            doFinished(assetFlit,user);
        }

        rMap.put("message", "提交成功");
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    //审批
    @RequestMapping(value = "approve", method = RequestMethod.POST)
    public Object approve(@CurrentUser User user, String keyId,  String curDutyId, String comment){
        Map<String,Object> rMap=new HashMap<String,Object>();
        AssetFlit assetFlit=assetFlitService.get(keyId);
        assetFlitService.approve(assetFlit, dutyService.get(curDutyId), comment);

        if(assetFlit.getProcessState().name().equals("Finished")){
            doFinished(assetFlit,user);
        }

        rMap.put("message","提交成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    public void doFinished(AssetFlit assetFlit,User user){
        assetFlit.setDateApply(new Date());
        assetFlit.setNumStatus(1);
        assetFlit.setTxtStatus("已调拨");
        assetFlitService.update(assetFlit);

        Asset asset = assetFlit.getAsset();
        asset.setTxtStatus("使用中");
        asset.setUser(assetFlit.getUser());
        asset.setUserName(assetFlit.getUser().getName());
        asset.setUseDepartment(assetFlit.getUseDepartment());
        assetService.update(asset);

        // 生成资产使用登记表
        AssetUse assetUse = new AssetUse();
        assetUse.setCreater(user);
        assetUse.setCompany(user.getCompany());
        assetUse.setAsset(asset);
        assetUse.setName(asset.getName());
        assetUse.setUseDepartment(assetFlit.getUseDepartment());
        assetUse.setUser(assetFlit.getUser());
        assetUse.setForm("资产使用登记表");
        assetUse.setDateApply(new Date());
        assetUse.setNumStatus(2);
        assetUse.setTxtStatus("已调拨");
        assetUse.setProcessState(FlowEnum.ProcessState.Finished);
        assetUseService.saveEntity(assetUse);
    }

    /**
     * 退回
     * @return
     */
    @RequestMapping(value = "back", method = RequestMethod.POST)
    public Object back(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            AssetFlit assetFlit=assetFlitService.get(keyId);
            assetFlitService.back(assetFlit, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","退回成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }
    /**
     * 否决
     * @return
     */
    @RequestMapping(value = "deny", method = RequestMethod.POST)
    public Object deny(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            AssetFlit assetFlit=assetFlitService.get(keyId);
            assetFlitService.deny(assetFlit, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","否决成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     * 列表
     */
    @RequestMapping(value = "list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> list(@CurrentUser User user,
                                    String viewtype, @RequestParam(required = false) String assetId,
                                    JqGridPager pager,
                                    @RequestJsonParam(value = "filters", required = false) JqGridFilter filters) {
        Company company = user.getCompany();
        // 排序
        Order order = Order.order("createTime", SearchEnum.OrderType.desc);

        SearchResultPaging searchResult = null;

        List<Rule> rules = getSearchFilterRules(pager.getSearch(), filters);
        rules.add(RuleHelper.eq("company", company));
        rules.add(RuleHelper.eq("state", BaseEnumManager.StateEnum.Enable));

        if (!StringUtils.isEmpty(assetId)) {
            rules.add(RuleHelper.eq("asset.id", assetId));  // 所属一个资产下的使用登记表
        }

        if(StringUtils.isNotEmpty(viewtype)) {
            if (viewtype.equals("1")) {
                //申请中
                searchResult = assetFlitService.paging(null,rules,order,
                        "com.fz.us.oa.core.entity.com.AssetFlit", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed},null);
            }else if(viewtype.equals("2")){
                //已调拨
                rules.add(RuleHelper.eq("numStatus", 1));
                searchResult = assetFlitService.paging(null,rules,order,
                        "com.fz.us.oa.core.entity.com.AssetFlit", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished},null);
            }
        }else{
            //所有
            searchResult = assetFlitService.paging(null,rules,order,
                    "com.fz.us.oa.core.entity.com.AssetFlit", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed},null);
        }
//        searchResult = assetFlitService.findPagingBySearch(null, rules, order);

        List<AssetFlit> assetFlitList = searchResult.getList();
        ArrayList<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        for(AssetFlit assetFlit: assetFlitList){
            rMap = new HashMap<String, Object>();
            rMap.put("id", StringUtils.isEmpty(assetFlit.getId())?"":assetFlit.getId());

            if(assetFlit.getCreateTime() != null){
                dateApply = assetFlit.getCreateTime();
                rMap.put("year", yearFormat.format(dateApply));   // 年份
                rMap.put("month", monthFormat.format(dateApply));   // 月份
                rMap.put("dateApply",dateFormat.format(dateApply));
            } else {
                rMap.put("year", "");   // 年份
                rMap.put("month", "");   // 月份
                rMap.put("dateApply","");
            }

            asset = assetFlit.getAsset();
            if(asset!=null){
                rMap.put("assetNo", asset.getAssetNo());
            }

            rMap.put("name", assetFlit.getName());
            rMap.put("oldUserName", assetFlit.getOldUserName());
            rMap.put("user", assetFlit.getUser()==null?"": assetFlit.getUser().getName());
            rMap.put("txtStatus", assetFlit.getTxtStatus());

//        map.put("processStateName", entity.getProcessState()==null?"": entity.getProcessState().value());
//        map.put("createTime", entity.getCreateTime()==null?"": DataUtil.DateTimeToString(entity.getCreateTime()));
            dataRows.add(rMap);
        }
        data.put("dataRows", dataRows);
        data.put("page", searchResult.getPageNumber());
        data.put("rows", searchResult.getPageSize());
        data.put("records", searchResult.getTotalCount());
        data.put("total", searchResult.getPageCount());
        return data;
    }

}
